const http = require('http');
const urlModule = require('url');
const fs = require('fs');
const path = require('path');

const server = http.createServer();


server.on('request',(req,res)=>{
    //获取静态资源路径
    //解析前端发送的request中，用户传过来ur路由
    let url = urlModule.parse(req.url).pathname
    if(url === '/' || url === '/index.html'){
        //调取静态首页资源
        //拿取资源的时候一定要是绝对路径
        //动态地配置绝对路径
        fs.readFile(path.join(__dirname,'static/index.html'),'utf-8',(err,data)=>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-Type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    }else if(url === '/product.html'){
        //调取静态资源
        fs.readFile(path.join(__dirname,'static/product.html'),'utf-8',(err,data)=>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-Type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    }else if(url === '/images/pro-1.jpg'){
        //调取静态资源
        fs.readFile(path.join(__dirname,'static/images/pro-1.jpg'),(err,data)=>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-Type','image/jpeg')
                res.end(data)
            }
        })
        
    }else if(url === '/images/pro-2.jpg'){
        //调取静态资源
        fs.readFile(path.join(__dirname,'static/images/pro-2.jpg'),(err,data)=>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-Type','image/jpeg')
                res.end(data)
            }
        })
    }
    else if(url === '/css/main.css'){
        //调取静态资源
        fs.readFile(path.join(__dirname,'static/css/main.css'),'utf-8',(err,data)=>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-Type','text/css;charset=utf-8')
                res.end(data)
            }
        })
    }
    else{
        //调取静态资源404
         fs.readFile(path.join(__dirname,'static/404.html'),'utf-8',(err,data)=>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-Type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    }
});


server.listen(3000),()=>{
    console.log('listen port 3000');
}